package cn.thoughtworks.school.services;

import cn.thoughtworks.school.commands.CreateUserCommand;
import cn.thoughtworks.school.entities.User;
import cn.thoughtworks.school.exceptions.BusinessException;
import cn.thoughtworks.school.feign.AuthCenterFeign;
import cn.thoughtworks.school.feign.UserCenterFeign;
import cn.thoughtworks.school.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

@Service
public class UserCenterService {
  public static final String CODE = "1054950364751.93627233200247900000.184";
  @Autowired
  private AuthCenterFeign authCenterFeign;
  @Autowired
  private UserRepository userRepository;
  @Autowired
  private UserCenterFeign userCenterFeign;

  public Map register(CreateUserCommand createUserCommand) throws BusinessException {
    Map token;
    try {
      token = authCenterFeign.register(createUserCommand).getBody();
    } catch (Exception e) {
      e.printStackTrace();
      String message = e.getMessage();
      message = message.split("message")[1];
      message = message.substring(3, message.length() - 2);
      throw new BusinessException(message);
    }

    User user = createUserCommand.buildRegisterUser(Long.parseLong(token.get("userId").toString()));
    userRepository.save(user);

    return token;
  }

  public void joinActivity(CreateUserCommand createUserCommand) throws BusinessException {
    Map userDetail = userCenterFeign.getUser(createUserCommand.getUserId());
    userCenterFeign.modifyUserDetail(createUserCommand.getUserId(), createUserCommand.updateUserDetail(userDetail));
    User user = userRepository.findByUserId(createUserCommand.getUserId()).orElseThrow(
        () -> new BusinessException("当前账号未注册"));
    if(Objects.nonNull(user.getJoinActivityTime())){
      throw new BusinessException("用户已报名！");
    }
    user = createUserCommand.completeUser(user);
    userRepository.save(user);
    createUserCommand.setCode(CODE);
    authCenterFeign.JoinProgramByUserId(createUserCommand.getUserId(), createUserCommand);
  }

  public Map usernameLogin(CreateUserCommand createUserCommand) throws BusinessException {
    Map loginUser;
    try {
      loginUser = authCenterFeign.usernameLogin(createUserCommand);
      if(!userRepository.findByUserId(Long.parseLong(loginUser.get("userId").toString())).isPresent()){
        User user = createUserCommand.buildRegisterUser(Long.parseLong(loginUser.get("userId").toString()));
        userRepository.save(user);
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new BusinessException("用户名或密码错误！");
    }
    return  loginUser;
  }
}
